import axios from 'axios'
import qs from 'qs'
import Vue from 'vue'

const api = {}
let ajaxUrl = 'http://vote.uue.cn'
if (process.env.NODE_ENV === 'development') {
  ajaxUrl = 'http://localhost:34568'
}

api.http = axios.create({
  timeout: 30000
})

// 添加请求拦截器
api.http.interceptors.request.use(
  function (config) {
    Vue.$vux.loading.show({
      text: '加载中'
    })
    // config.headers['Accept'] = 'application/x.edu.v1+json';
    if (config.method === 'post' || config.method === 'put') {
      config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
      config.data = qs.stringify(config.data)
    }
    return config
  },
  function (error) {
    setTimeout(() => {
      Vue.$vux.loading.hide()
      Vue.$vux.toast.show({
        text: '加载超时',
        position: 'middle',
        type: 'warn'
      })
    }, 3000)
    return Promise.reject(error)
  }
)

// 添加响应拦截器
api.http.interceptors.response.use(
  function (response) {
    Vue.$vux.loading.hide()
    if (response.status === 200) {
      console.log(response.data)
      return response.data
    }
    return response
  },
  function (error) {
    let msg = '请求失败'
    if (error.response.data.msg) {
      msg = error.response.data.msg
    }
    setTimeout(() => {
      Vue.$vux.loading.hide()
      Vue.$vux.toast.show({
        width: '20em',
        text: msg,
        position: 'middle',
        type: 'warn'
      })
    }, 1000)
    return Promise.reject(error.response.data.msg)
  }
)

api.get = function (url) {}

api.post = function (url, params) {}

api.put = function (url, params) {}

api.getLocalTime = function (nS) {
  return new Date(parseInt(nS) * 1000)
}

api.ajaxBaseUrl = ajaxUrl

api.url = {
  // 登录
  login: ajaxUrl + '/api/home/login',
  list: ajaxUrl + '/api/home/votes'
}

export default api
